<template>
  <!-- 消防报表 -->
  <div>
    <el-row type="flex" justify="space-between">
      <el-form class="serach-form" ref="searchForm" :model="searchForm" :inline="true" @submit.native.prevent>
        <el-form-item>
          <el-input placeholder="请输入报表名称" v-model="searchForm.queryContent" @keyup.enter.native="search" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button class="form-search-btn" type="primary" @click="search">查询</el-button>
        </el-form-item>
      </el-form>
      <div class="more-btns">
        <el-button v-if="showDownload" type="primary" @click="openDownload">自动生成报表</el-button>
      </div>
    </el-row>
    <el-row class="overclick-wrap" :gutter="20" type="flex" justify="space-between">
      <el-col :span="5">
        <div class="item-wrap" @click="searchForm.period=0" :class="searchForm.period==0 ? 'active' : ''">
          <div class="item-content">
            <p class="item-value color-4">{{ reportStatistics.total || 0 }}</p>
            <p class="item-title">报表总数（个）</p>
          </div>
        </div>
      </el-col>
      <el-col :span="5">
        <div class="item-wrap" @click="searchForm.period=1" :class="searchForm.period==1 ? 'active' : ''">
          <div class="item-content">
            <p class="item-value color-3">{{ reportStatistics.weekTotal || 0 }}</p>
            <p class="item-title">消防周报</p>
          </div>
        </div>
      </el-col>
      <el-col :span="5">
        <div class="item-wrap" @click="searchForm.period=2" :class="searchForm.period==2 ? 'active' : ''">
          <div class="item-content">
            <p class="item-value color-2">{{ reportStatistics.monthTotal || 0 }}</p>
            <p class="item-title">消防月报</p>
          </div>
        </div>
      </el-col>
      <el-col :span="5">
        <div class="item-wrap" @click="searchForm.period=5" :class="searchForm.period==5 ? 'active' : ''">
          <div class="item-content">
            <p class="item-value color-5">{{ reportStatistics.quarterTotal || 0 }}</p>
            <p class="item-title">消防季报</p>
          </div>
        </div>
      </el-col>
      <el-col :span="4">
        <div class="item-wrap" @click="searchForm.period=3" :class="searchForm.period==3 ? 'active' : ''">
          <div class="item-content">
            <p class="item-value color-1">{{ reportStatistics.yearTotal || 0 }}</p>
            <p class="item-title">消防年报</p>
          </div>
        </div>
      </el-col>
    </el-row>
    <div>
      <el-table v-loading="loading" ref="singleUnitTableList" :data="tableData" style="width: 100%">
        <el-table-column label="序号" type="index" width="50"></el-table-column>
        <el-table-column label="报表名称" prop="picturesUrls">
          <template slot-scope="scope">
            <el-link type="primary" @click="viewReport(scope.row)">{{ setReportName(scope.row) }}</el-link>
          </template>
        </el-table-column>
        <el-table-column label="报告周期" prop="period" width="200">
          <template slot-scope="scope">
            <el-link>{{ getPeriodName(scope.row.period)}}</el-link>
          </template>
        </el-table-column>
        <el-table-column label="报告期" prop="ranges" width="300"></el-table-column>
        <el-table-column label="生成时间" prop="createTime" width="200"></el-table-column>
      </el-table>
      <el-pagination
        background
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
        :current-page.sync="currentPage"
        :page-sizes="[10, 50, 100]"
        :page-size="10"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>
    <!-- 查看报表 -->
    <el-dialog
      :close-on-click-modal="false"
      title="报表详情"
      width="600px"
      top="2vh"
      v-if="dialogReportDetail"
      :visible.sync="dialogReportDetail"
      @close="closeDialog"
      v-dialogDrag
    >
      <fire-report-detail v-if="dialogReportDetail" :reportAttr="currentReportData"></fire-report-detail>
    </el-dialog>
    <el-dialog
      :close-on-click-modal="false"
      title="自动生成报表"
      width="600px"
      v-if="dialogDownload"
      :visible.sync="dialogDownload"
      @close="closeDialogDownload"
      v-dialogDrag
    >
      <el-form ref="dataForm" :model="dataForm" :rules="dataFormRule" @submit.native.prevent>
        <el-form-item prop="time">
          <el-date-picker
            v-model="dataForm.time"
            type="daterange"
            align="right"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions"
            style="width:100%;"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label-width="0" class="verifyidentity-button">
          <el-button @click="closeDialogDownload">取消</el-button>
          <el-button type="primary" @click="handleDownload">确定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import util from '@/utils/util'
import FireReportDetail from './Dialog/FireReportDetail'
import { getFireReportList, getFireReportCount } from '@/api/maintenanceReport'
import { downloadExcel } from '@/utils/downloadUtil'

export default {
  name: 'FireReport',
  components: {
    FireReportDetail,
  },
  data() {
    return {
      loading: true,
      searchForm: {
        queryContent: '',
        period: 0,
      },
      reportStatistics: {
        total: 0,
        weekTotal: 0,
        yearTotal: 0,
      },
      // 列表
      tableData: [],
      // 分页
      currentPage: 1,
      pageSize: 10,
      total: 0,
      dialogReportDetail: false, // 报表弹框
      currentReportData: {},
      showDownload: CONFIGKEY == 'kshqxf',
      downloadLoading: false,
      dialogDownload: false,
      pickerOptions: util.intTimePickerOptions(),
      dataForm: {
        time: [],
      },
      dataFormRule: {
        time: [{ required: true, message: '请选择' }],
      },
    }
  },
  mounted() {
    this.search()
    let moment = this.$moment().subtract(1, 'months')
    this.dataForm.time = [
      moment
        .startOf('month')
        .hours(0)
        .minutes(0)
        .seconds(0)
        .format('yyyy-MM-DD'),
      moment
        .endOf('month')
        .hours(0)
        .minutes(0)
        .seconds(0)
        .format('yyyy-MM-DD'),
    ]
  },
  methods: {
    openDownload() {
      this.dialogDownload = true
    },
    closeDialogDownload() {
      this.dialogDownload = false
    },
    handleDownload() {
      this.$refs.dataForm.validate((valid) => {
        if (valid) {
          if (
            this.dataForm.time[0].substr(0, 4) !=
            this.dataForm.time[1].substr(0, 4)
          ) {
            this.$message.warning('报表日期不能跨年')
          } else {
            this.downloadLoading = true
            fetch(
              this.GLOBAL.baseURL +
                `org/exportPlatData?startTime=${this.dataForm.time[0]} 00:00:00&endTime=${this.dataForm.time[1]} 23:59:59`
            )
              .then((res) => res.blob())
              .then((blob) => {
                downloadExcel(
                  blob,
                  '统计报表' +
                    this.dataForm.time[0] +
                    '~' +
                    this.dataForm.time[1] +
                    '.xlsx'
                )
                this.$message.success('导出成功')
                this.downloadLoading = false
                this.closeDialogDownload()
              })
              .catch((e) => {
                this.$message.error('导出失败')
                this.downloadLoading = false
              })
          }
        }
      })
    },
    getPeriodName(v) {
      return ['', '周', '月', '年', '年', '季'][v] || ''
    },
    getStatisticsData() {
      let that = this

      getFireReportCount({
        queryContent: that.searchForm.queryContent || '',
      }).then((res) => {
        that.reportStatistics = { ...res.data }
      })
    },
    // 获取列表数据
    getTableData(pageIndex, pageSize) {
      let that = this
      that.loading = true
      if (pageIndex) {
        that.currentPage = pageIndex
      }
      if (pageSize) {
        that.pageSize = pageSize
      }
      let parames = {
        queryContent: that.searchForm.queryContent || '',
        period: that.searchForm.period == 0 ? '' : that.searchForm.period,
        pageSize: that.pageSize,
        pageIndex: that.currentPage - 1,
      }
      // 获取列表信息
      getFireReportList(parames).then((res) => {
        that.tableData = res.data
        that.total = res.total
        that.loading = false
      })
    },
    handleSizeChange(pageSize) {
      this.getTableData(1, pageSize)
    },
    handleCurrentChange(currentPage) {
      this.getTableData(currentPage, this.pageSize)
    },
    search() {
      this.getStatisticsData()
      this.getTableData(1)
    },
    getReportName(v) {
      return ['', '周报', '月报', '单位年报', '平台年报', '季报'][v] || ''
    },
    // 设置报表名称
    setReportName(obj) {
      return obj.ranges + obj.reportName + this.getReportName(obj.period)
    },
    viewReport(data) {
      this.currentReportData = data
      this.dialogReportDetail = true
    },
    closeDialog() {
      this.dialogReportDetail = false
    },
  },
  watch: {
    period(val, oldVal) {
      if (val !== oldVal) {
        this.getTableData(1)
      }
    },
  },
  computed: {
    period() {
      return this.searchForm.period
    },
  },
}
</script>